package action;

import global.Constants;
import global.security.SessionUtils;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import util.FileUtils;
import util.MessageUtils;
import util.ServletHelp;

/**
 * 文件上传Action类.
 * <p>
 * 创建日期：2010-07-01<br>
 * 创建人：Xiyt<br>
 * 修改日期：<br>
 * 修改人：<br>
 * 修改内容：<br>
 * 
 * @author Xiyt
 * @version 1.0
 */
public class FileUploadAction extends BaseAction {

	@SuppressWarnings("unchecked")
	public ActionForward uploadFileToDisk(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 上传文件的保存路径
		String uploadFilePath = ServletHelp.getRealPath(request,
				MessageUtils.setParamMessage(Constants.UPLOAD_PICTURE_PATH, new String[]{SessionUtils.getCurrentUserId()}));

		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List items = null;
		// 得到所有的文件：
		items = (List) upload.parseRequest(request);
		Iterator it = items.iterator();
		while (it.hasNext()) {
			// 依次处理每一个文件：
			FileItem fi = (FileItem) it.next();
			if (Constants.UPLOAD_FILE_PARAM_NAME.equals(fi.getFieldName())) {
				// 获得文件名，这个文件名包括路径：
				FileUtils.writeFileToDisk(fi.get(), uploadFilePath + "\\" + fi.getName());
			}
		}

		// 返回结果
		JSONObject res = new JSONObject();
		res.put("success", true);
		ServletHelp.outRequestForJson(request, response, res.toString());
		return null;
	}
}
